/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.numbers.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.Formatting;
import axil.api.Persona;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

import static axil.framework.Functions.*;


/**
 * An Axil representation of an integer value that exceeds a 32-bit signed
 * integer.
 */
public class BigInt extends Num {
	public static final AxilType type = new BigInt_Type();
	public static final BigInt zero = new BigInt(BigInteger.ZERO);

	private final BigInteger value;


	public BigInt(BigInteger value) {
		this.value = value;
	}


	public BigInt(long value) {
		this.value = new BigInteger(Long.toString(value));
	}


	public static BigInt from(BigInteger value) {
		if (value == BigInteger.ZERO) {
			return zero;
		}
		return new BigInt(value);
	}


	public static BigInt from(long value) {
		if (value == 0L) {
			return zero;
		}
		return new BigInt(value);
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Return the canonical representation of a zero value in this numeric
	 * type.
	 */
	public Num zero() {
		return zero;
	}


	/**
	 * Tell the magnitude of this numeric value. This is used in all arithmetic
	 * computations to ensure like objects are used.
	 */
	public int kind() {
		return BIGINT;
	}


	/**
	 * Return the value of this object as an object of the indicated size. It
	 * can be safely assumed that the caller intended whatever side effects
	 * occur as part of the conversion are intentional.
	 */
	public Num as(int kind) {
		switch(kind) {
		case INT:
			return Int.from(value.intValue());
		case BIGINT:
			return this;
		case FRACTION:
			return new Fraction(value.intValue(), 1);
		case FP:
			return FloatingPoint.from(value.doubleValue());
		case DECIMAL:
			return new Decimal(new BigDecimal(value));
		case PERCENT:
			return new Percent(this);

		default:
			throw abort("Unrecognized kind", nv("kind", kind));
		}
	}


	/**
	 * Tell if this number has any significant fractional digits. For example,
	 * the number 3.1 would return true, but 3.0 would not.
	 */
	public boolean fractional() {
		return false;
	}


	/**
	 * Get this value as an integer value, discarding any fractional component.
	 * For example, 12.65 returns the integer value 12. No rounding is performed,
	 * only truncation. If the value is greater than what can fit in a 64-bit
	 * integer, then an exception is thrown.
	 */
	public long whole() {
		return value.longValue();
	}


	/**
	 * Get the fractional portion of this numeric value as a floating point
	 * value. For example, 12.325 returns a value of 0.325. If there is no
	 * fractional portion, then 0.0 is returned.
	 */
	public double tenths() {
		return 0;
	}


	/**
	 * Return a true value if this number is greater than zero. A value of zero
	 * returns a false value.
	 */
	public boolean positive() {
		return value.signum() > 0;
	}


	/**
	 * Return a floating point representation of this object. It is understood
	 * the some loos of information may result. Invoking this method is
	 * accepting that side effect.
	 */
	public double fp() {
		return value.doubleValue();
	}


	/**
	 * Returns a hash code value for the object. All Axil values must provide a
	 * meaningful implementation of this function to enable themselves to be
	 * placed in a map or set.
	 */
	protected int hash() {
		return value.hashCode();
	}


	private boolean eq(Num v) {
		return this.value.equals(((BigInt)v).value);
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		if (object instanceof Num) {
			Num n = (Num)object;
			if (n.fractional()) {
				return false;
			}
			switch(n.kind()) {
			case INT:
				return eq(n.as(BIGINT));
			case BIGINT:
				return eq(n);
			case FRACTION:
				return eq(n.as(BIGINT));
			case FP:
				return n.fp() == this.fp();
			case DECIMAL:
				return as(DECIMAL).equalTo(n);
			case PERCENT:
				return as(PERCENT).equals(n);
			case UNITIZED:
				return equalTo(mag(n));
			default:
				throw unreachable();
			}
		}
		return false;
	}


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, a ClassCastException may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
	public int comparedTo(AxilObject object) {
		if (object instanceof BigInt) {
			BigInt v = (BigInt)object;
			return value.compareTo(v.value);
		}
		Num n = num(object);
		int kind = upcast(this, n);
		return as(kind).comparedTo(n.as(kind));
	}


	/**
	 * Add the given number of this number.
	 */
	public AxilObject add(AxilObject n) {
        if (n instanceof BigInt) {
            BigInt v = (BigInt)n;
            return from(value.add(v.value));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).add(v.as(kind));
        }
	}


	/**
	 * Subtract the given number from this number.
	 */
	public AxilObject subtract(AxilObject n) {
        if (n instanceof BigInt) {
            BigInt v = (BigInt)n;
            return from(value.subtract(v.value));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).subtract(v.as(kind));
        }
	}


	/**
	 * Multiply the given number by this number.
	 */
	public Num multiply(Num n) {
        if (n instanceof BigInt) {
            BigInt v = (BigInt)n;
            return from(value.multiply(v.value));
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).multiply(v.as(kind));
        }
	}


	/**
	 * Divide this number by the given number.
	 */
	public Num divide(Num n) {
        if (n instanceof BigInt) {
            BigInt v = (BigInt)n;
            BigDecimal r = new BigDecimal(value).divide(new BigDecimal(v.value));
            if (r.scale() > 0) {
                return new Decimal(r);
            }
            return new BigInt(r.toBigInteger());
        } else {
            Num v = num(n);
            int kind = upcast(this, v);
            return as(kind).divide(v.as(kind));
        }
	}

	/**
	 * Round this value according to the rules of the given rounding mode and
	 * to the given number of significant fractional digits. A value of zero
	 * rounds this to a whole number.
	 */
	public Num round(RoundingMode mode, int digits) {
		return this;
	}

	/**
	 * Parse the given text as a representation of the canonical form of this
	 * type. A null is returned if the text does not represent a valid object.
	 * The string given cannot be null.
	 */
	public BigInt parse(String text) {
		BigInt v = null;
		try {
			BigInteger i = new BigInteger(text);
			v = from(i);
		} catch (NumberFormatException e) {
			// IGNORED
		}
		return v;
	}

	/**
	 * Return an integer representation of this object, or the nearest integer
	 * value to this object. If this object has no meaningful numeric
	 * representation, then an exception is thrown.
	 *
	 * @return
	 * 	Returns the nearest integer value.
	 */
	public int asInteger() {
		return value.intValue();
	}


	/**
	 * Return a long representation of this object, or the nearest long
	 * value to this object. If this object has no meaningful numeric
	 * representation, then an exception is thrown.
	 *
	 * @return
	 * 	Returns the nearest long integer value.
	 */
	public long asLong() {
		return value.longValue();
	}


	/**
	 * Return a floating point representation of this object. If this object has
	 * no meaningful numeric representation, then an exception is thrown.
	 *
	 * @return
	 * 	Returns this object as a floating point value.
	 */
	public double asFloatingPoint() {
		return value.doubleValue();
	}


	/**
	 * Return a decimal representation of this object. If this object has
	 * no meaningful numeric representation, then an exception is thrown.
	 *
	 * @return
	 * 	Returns this object as a decimal value.
	 */
	public BigDecimal asDecimal() {
		return new BigDecimal(value);
	}


	/**
	 * Returns a hash code value for the object. This method is supported for
	 * the benefit of hash tables and such. By default, numbers return the
	 * nearest integer representation of this object.
	 */
	public int hashCode() {
		return value.hashCode();
	}


	/**
	 * Return the host application (or built-in Java) object that most closely
	 * matches this value object. Return returned value is never null unless
	 * this value object represents the special 'nil' object.
	 */
	public Object intrinsic() {
		return value;
	}


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		// TODO: Need better formatting support here
		return value.toString();
	}
}
